package com.sq.partner.manager.controller;




import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.common.DictCache;
import com.sq.partner.manager.common.Result;
import com.sq.partner.manager.mybatis.model.CoreDept;
import com.sq.partner.manager.mybatis.model.DictDto;
import com.sq.partner.manager.mybatis.model.GatewayChannelInfo;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.mybatis.model.TradAgentInfo;
import com.sq.partner.manager.mybatis.model.TradInsuPlan;
import com.sq.partner.manager.mybatis.model.TradInsuPlanGroup;
import com.sq.partner.manager.mybatis.model.TradPlanGroup;
import com.sq.partner.manager.mybatis.model.TradProdInst;
import com.sq.partner.manager.mybatis.model.TradSmsTemplate;
import com.sq.partner.manager.service.IGatewayChannelInfoConfigService;
import com.sq.partner.manager.service.IGatewayInsureService;
import com.sq.partner.manager.service.IGatewayProductService;
import com.sq.partner.manager.service.ITradInsuPlanGroupService;
import com.sq.partner.manager.service.ITradPlanGroupService;
import com.sq.partner.manager.service.TradSmsTemplateService;
import com.sq.partner.manager.util.JsonUtils;
import com.sq.partner.manager.util.LogUtil;
import com.sq.partner.manager.util.Page;
import com.sq.partner.manager.util.StrUtil;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
/**
 * 
 * @author duguangwei
 * 投保方案定义 insure
 * TradInsuPlan
 */
@Controller
@RequestMapping("/insure")
public class InsureController {
	
	private static Logger logger = LogUtil.getLog(InsureController.class);

	@Resource
	IGatewayInsureService gatewayInsureService;

	@Resource
	IGatewayProductService productService;	

	@Resource
	ITradInsuPlanGroupService insuPlanGroupService; 
	
	@Resource
	ITradPlanGroupService plangroupService; 
	
	@Resource
	private IGatewayChannelInfoConfigService channelInfoConfigService;
	
	@Resource
	private TradSmsTemplateService tradSmsTemplateService;
	
	@RequestMapping(value = "/list")
	public String insureDefinition(ModelMap model,HttpServletRequest request) throws Exception {
		
		return "product/insure/list";
	}
	
	//添加 投保方案成功后，传入一个参数标识在list页面提示
	@RequestMapping(value = "/success")
	public String noticeSuccess(HttpServletRequest request,String flag) throws Exception {
		request.setAttribute("flag", flag);
		logger.info("flag================================================"+flag);
		return "product/insure/list";
	}
	
	//跳转至新增页面
	@RequestMapping(value = "/add")
	public String insureAdd(ModelMap model,HttpServletRequest request) throws Exception {
		//页面初始化加载“保险公司”列表
		List<DictDto> list = DictCache.getDict("insure_company");
		model.put("companyList", list);

		//页面初始化加载“共保角色”列表
		List<DictDto> rolelist = DictCache.getDict("pool_role");
		model.put("roleList", rolelist);
		
		//页面初始化加载“附件发送类型”列表
		List<DictDto> Accessorylist=DictCache.getDict("acc_type");
		model.put("Accessorylist",Accessorylist );
		//新业务来源
		List<DictDto> newBSList = DictCache.getDict(Constants.DICT_NEW_BUSINESS_SOURCE);
		//旧业务来源
		List<DictDto> oldBSList = DictCache.getDict(Constants.DICT_OLD_BUSINESS_SOURCE);
		//归属渠道
		List<DictDto> btcList = DictCache.getDict(Constants.DICT_BELONG_TO_CHANNEL);
		//渠道类型
		List<DictDto> channelList = DictCache.getDict(Constants.DICT_CHANNEL_TYPE);
		List<DictDto> receiptTypeLs = DictCache.getDict(Constants.DICT_RECEIPT_TYPE_OPTIONS);
		//初始化承保短信模板
		List<TradSmsTemplate> messageList = tradSmsTemplateService.queryTrade(Constants.MESSAGETEMPLATE_TYPE);
		//初始化注销短信模板
		List<TradSmsTemplate> cacelList = tradSmsTemplateService.queryTrade(Constants.CANCELTEMPLATE_TYPE);
		//电子保单文件方式
		List<DictDto> fileTypes = DictCache.getDict(Constants.DICT_FILE_TYPE);
		model.put("newBSList", newBSList);
		model.put("oldBSList", oldBSList);
		model.put("btcList", btcList);
		model.put("channelList", channelList);
		model.put("receiptTypeLs", receiptTypeLs);
		model.put("messageList", messageList);
		model.put("cacelList", cacelList);
		model.put("fileTypes", fileTypes);
		return "product/insure/add";
	}
	

	
	//查询短信模板信息
	@RequestMapping(value = "/loadTemplate")
	public @ResponseBody TradSmsTemplate loadTemplate(String smsTemplateCode) throws Exception{
		return tradSmsTemplateService.queryTradeByCode(smsTemplateCode);
	}
	
	//跳转至编辑页面
	@RequestMapping(value = "/edit")
	public String insureEdit(ModelMap model,HttpServletRequest request,String insuPlanNo) throws Exception {
		request.setAttribute("insuPlanNo",insuPlanNo);
		model.put("insuPlanNo", insuPlanNo);
		
		//页面初始化加载“附件发送类型”列表
		List<DictDto> Accessorylist=DictCache.getDict("acc_type");
		model.put("AccessoryEditlist",Accessorylist );
		//页面初始化加载“保险公司”列表
		List<DictDto> list = DictCache.getDict("insure_company");
		model.put("companyList", list);

		//页面初始化加载“共保角色”列表
		List<DictDto> rolelist = DictCache.getDict("pool_role");
		model.put("roleList", rolelist);

		//根据方案号查询对应产品的共保类型和投保类型
		TradInsuPlan tp = new TradInsuPlan();
		tp.setInsuPlanNo(insuPlanNo);
		TradInsuPlan InsuPlan = gatewayInsureService.queryTradInsuPlanInfo(tp);
		//added by gzz@20150824 begin
		if(null!=InsuPlan && StrUtil.isNotEmpty(InsuPlan.getPartnerNo())){
			String applicationNo = "";
			GatewayChannelInfo temObj = channelInfoConfigService.queryChannelInfoByChannelCode(InsuPlan.getPartnerNo());
			applicationNo = temObj.getClientNo();
			model.put("realClientNo", applicationNo);
		}
		//added by gzz@20150824 end
		TradProdInst tempProd = new TradProdInst();
		tempProd.setTradProdCode(InsuPlan.getTradProdCode());
		TradProdInst prod = productService.queryTradProdInst(tempProd);

		model.put("poolTypeVal", prod.getPoolType());//共保类型
		
		model.put("appType", prod.getTradAppType());//投保类型
		//新业务来源
		List<DictDto> newBSList = DictCache.getDict(Constants.DICT_NEW_BUSINESS_SOURCE);
		//旧业务来源
		List<DictDto> oldBSList = DictCache.getDict(Constants.DICT_OLD_BUSINESS_SOURCE);
		//归属渠道
		List<DictDto> btcList = DictCache.getDict(Constants.DICT_BELONG_TO_CHANNEL);
		//渠道类型
		List<DictDto> channelList = DictCache.getDict(Constants.DICT_CHANNEL_TYPE);
		List<DictDto> receiptTypeLs = DictCache.getDict(Constants.DICT_RECEIPT_TYPE_OPTIONS);
		//初始化承保短信
		List<TradSmsTemplate> messageList = tradSmsTemplateService.queryTrade(Constants.MESSAGETEMPLATE_TYPE);
		//初始化注销短信
		List<TradSmsTemplate> cacelList = tradSmsTemplateService.queryTrade(Constants.CANCELTEMPLATE_TYPE);
		//电子保单文件方式
		List<DictDto> fileTypes = DictCache.getDict(Constants.DICT_FILE_TYPE);
		model.put("newBSList", newBSList);
		model.put("oldBSList", oldBSList);
		model.put("btcList", btcList);
		model.put("channelList", channelList);
		model.put("receiptTypeLs", receiptTypeLs);
		model.put("messageList", messageList);
		model.put("cacelList", cacelList);
		model.put("fileTypes", fileTypes);
		return "product/insure/add";
	}
	
	//跳转至复制添加页面
	@RequestMapping(value = "/copyadd")
	public String insureCopyAdd(ModelMap model,HttpServletRequest request,String insuPlanNo) throws Exception {
		logger.info("===================================================="+insuPlanNo);
		request.setAttribute("insuPlanNo",insuPlanNo);
		model.put("insuPlanNo", insuPlanNo);
		//页面初始化加载“附件发送类型”列表
		List<DictDto> Accessorylist=DictCache.getDict("acc_type");
		model.put("Accessorylist",Accessorylist );
		
		//页面初始化加载“保险公司”列表
		List<DictDto> list = DictCache.getDict("insure_company");
		model.put("companyList", list);

		//页面初始化加载“共保角色”列表
		List<DictDto> rolelist = DictCache.getDict("pool_role");
		model.put("roleList", rolelist);

		TradInsuPlan tp = new TradInsuPlan();
		tp.setInsuPlanNo(insuPlanNo);
		TradInsuPlan InsuPlan = gatewayInsureService.queryTradInsuPlanInfo(tp);
		//added by gzz@20150824 begin
		if(null!=InsuPlan && StrUtil.isNotEmpty(InsuPlan.getPartnerNo())){
			String applicationNo = "";
			GatewayChannelInfo temObj = channelInfoConfigService.queryChannelInfoByChannelCode(InsuPlan.getPartnerNo());
			applicationNo = temObj.getClientNo();
			model.put("realClientNo", applicationNo);
		}
		//added by gzz@20150824 end
		TradProdInst tempProd = new TradProdInst();
		tempProd.setTradProdCode(InsuPlan.getTradProdCode());
		TradProdInst prod = productService.queryTradProdInst(tempProd);
		model.put("poolTypeVal", prod.getPoolType());
		//新业务来源
		List<DictDto> newBSList = DictCache.getDict(Constants.DICT_NEW_BUSINESS_SOURCE);
		//旧业务来源
		List<DictDto> oldBSList = DictCache.getDict(Constants.DICT_OLD_BUSINESS_SOURCE);
		//归属渠道
		List<DictDto> btcList = DictCache.getDict(Constants.DICT_BELONG_TO_CHANNEL);
		//渠道类型
		List<DictDto> channelList = DictCache.getDict(Constants.DICT_CHANNEL_TYPE);
		List<DictDto> receiptTypeLs = DictCache.getDict(Constants.DICT_RECEIPT_TYPE_OPTIONS);
		//初始化承保短信
		List<TradSmsTemplate> messageList = tradSmsTemplateService.queryTrade(Constants.MESSAGETEMPLATE_TYPE);
		//初始化注销短信
		List<TradSmsTemplate> cacelList = tradSmsTemplateService.queryTrade(Constants.CANCELTEMPLATE_TYPE);
		//电子保单文件方式
		List<DictDto> fileTypes = DictCache.getDict(Constants.DICT_FILE_TYPE);
		model.put("fileTypes", fileTypes);
		model.put("newBSList", newBSList);
		model.put("oldBSList", oldBSList);
		model.put("btcList", btcList);
		model.put("channelList", channelList);
		model.put("receiptTypeLs", receiptTypeLs);
		model.put("messageList", messageList);
		model.put("cacelList", cacelList);
	
		return "product/insure/copyAdd";
	}
	/**
	 * 加载投保方案
	 * @param size
	 * @param current
	 * @param tradPlanCode
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/loadInsuPlan")
	public @ResponseBody Page<TradInsuPlan> InsuPlan(HttpSession session,Integer size,Integer current,String tradProdCode,String insuPlanNo,String partnerNo,String insuPlanName) throws Exception{
		Page<TradInsuPlan> page=new Page<TradInsuPlan>();
		page.setCurrent(current);
		page.setSize(size);
		TradInsuPlan tradInsuPlan=new TradInsuPlan();
		//判断空
		tradInsuPlan.setInsuPlanNo(insuPlanNo);
		tradInsuPlan.setPartnerNo(partnerNo);
		tradInsuPlan.setInsuPlanName(insuPlanName);
		tradInsuPlan.setTradProdCode(tradProdCode);
		GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		page.setDepts(gatewayuser.getDepts());
		
		page.setType(tradInsuPlan);
		Page<TradInsuPlan> page2=gatewayInsureService.queryTradInsuPlanPage(page);
		return page2;
	}
	

	/**
	 * 加载所有 投保单位
	 * @param size
	 * @param current
	 * @return
	 * @throws Exception
	 * loadChannelInfo
	 */
	@RequestMapping(value = "/loadChannelInfo")
	public @ResponseBody Page<GatewayChannelInfo> loadChannelInfo(HttpSession session,Integer size,Integer pageIndex,String channelCode,String channelName) throws Exception{
		Page<GatewayChannelInfo> page = new Page<GatewayChannelInfo>();
		page.setCurrent(pageIndex);
		page.setSize(size);
		GatewayChannelInfo channelInfo = new GatewayChannelInfo();
		channelInfo.setChannelName(channelName);
		channelInfo.setChannelCode(channelCode);
		
		GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		page.setDepts(gatewayuser.getDepts());
		page.setType(channelInfo);
		Page<GatewayChannelInfo> p=gatewayInsureService.queryPageForGatewayChannelInfo(page);
		return p;
	}
	
	
	
	
	
	
	

	/**
	 * 加载 产品列表
	 * @param size
	 * @param pageIndex
	 * @param tradProdCode
	 * @param tradProdDesc
	 * @param startdate
	 * @param enddate
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/loadTradProdInst")
	public @ResponseBody Page<TradProdInst> queryAllTradProdInst(Integer size,Integer pageIndex,String tradProdCode,String tradProdDesc,String VstartDate,String VendDate) throws Exception{
		Page<TradProdInst> page=new Page<TradProdInst>();
		page.setCurrent(pageIndex);
		page.setSize(size);
		TradProdInst tradProdInst=new TradProdInst();
		//判断空
		tradProdInst.setTradProdCode(tradProdCode);
		tradProdInst.setTradProdDesc(tradProdDesc);
		tradProdInst.setVstartDate(VstartDate);
		tradProdInst.setVendDate(VendDate);
		page.setType(tradProdInst);
		Page<TradProdInst> page2=gatewayInsureService.queryPageForTradProdInst(page);
		return page2;
	}
	
	
	/**
	 * 加载机构列表，需要传入页面选择的“投保单位代码”进行查询
	 * @param size
	 * @param pageIndex
	 * @param deptCode
	 * @param deptCNname
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/loadCoreDept")
	public @ResponseBody Page<CoreDept> queryAllCoreDepts(Integer size,Integer pageIndex,String deptCode,String deptCNname,String channelCode) throws Exception{
		Page<CoreDept> page=new Page<CoreDept>();
		page.setCurrent(pageIndex);
		page.setSize(size);
		CoreDept dept=new CoreDept();
		dept.setDeptCode(deptCode);
		dept.setDeptCname(deptCNname);
		page.setType(dept);
		Page<CoreDept> page2=gatewayInsureService.queryPageForCoreDept(page,channelCode);
		return page2;
	}
	
	
	
	/**
	 * 添加 投保方案
	 * @param insuPlanNo
	 * @param insuPlanName
	 * @param tradProdCode
	 * @param partnerNo
	 * @param agentNo
	 * @param protocolNo
	 * @param commRate
	 * @param serviceCode
	 * @param empNo
	 * @param applicantNo
	 * @param isMessage
	 * @param channleCode
	 * @param channleType
	 * @param newBsnsType
	 * @param categoryCode
	 * @param endDate
	 * @param dptCde
	 * @param specialArran
	 * @param state
	 * @param EpolicyInvoice 
	 * @param DredgePay  
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/addTradInsuPlan")
	public @ResponseBody Result addTradInsuPlan(HttpSession session,String fileType,String insuPlanName,String tradProdCode,String partnerNo,String agentNo,String protocolNo,
			BigDecimal commRate,String serviceCode,String empNo,String teamCode,String teamName,String applicantNo,String isMessage,String channleCode,String channleType,String newBsnsType,
			String categoryCode,String endDate,String dptCde,String specialArran,String state,String isSeeMoney,String poolInsureCompany,String poolProcotol,
			String poolProcotolNo,String poolIssueFlag,BigDecimal poolAgentRate,BigDecimal poolRate,BigDecimal poolInsureAmount,String poolRole,
			String isPrintCard,String cardApplicant,String isEpolicy,String messageTemplate,String isReceipt,String messageReceiver,String cardType,String reminder, String receiptType ,
			String EpolicyInvoice, String DredgePay,String EpolicyMali,String MailTemplate ,String selectAccessorylistStr,String DownloadWay,String isCancelMessage,String cancelReceiver,String cancelTemplate) throws Exception{


		//首先进行非空、格式校验
		if(StrUtil.isEmpty(insuPlanName)){
			return Result.error("请输入投保方案名称");
		}
		if(StrUtil.isEmpty(tradProdCode)){
			return Result.error("请选择产品编号");
		}
		cancelTemplate=URLDecoder.decode(cancelTemplate, "UTF-8");
		//获取产品的投保类型：0 代表个单；1代表 团单
		TradProdInst prod1 = new TradProdInst();
		prod1.setTradProdCode(tradProdCode);
		TradProdInst prod2 = productService.queryTradProdInst(prod1);
		String appType = prod2.getTradAppType();
		
		
		if(StrUtil.isEmpty(partnerNo)){
			return Result.error("请选择合作伙伴代码");
		}
		
		//1、合作伙伴代理3、个人代理4、总对总代理
		if(!"3".equals(prod2.getAgentType())&&!"4".equals(prod2.getAgentType())){
			if(StrUtil.isEmpty(channleCode)){
				return Result.error("请选择归属渠道");
			}
			if(StrUtil.isEmpty(channleType)){
				return Result.error("请选择渠道类型");
			}
			if(StrUtil.isEmpty(newBsnsType)){
				return Result.error("请选择新业务来源");
			}
			if(StrUtil.isEmpty(categoryCode)){
				return Result.error("请选择原业务来源");
			}
			if(StrUtil.isEmpty(dptCde)){
				return Result.error("请选择出单机构");
			}
		}
		if(null == commRate){
			return Result.error("请输入手续费比例");
		}else{
			Pattern pattern = Pattern.compile("([1-9]\\d{0,15}|0)(\\.\\d{1,4})?");  
			Matcher matcher = pattern.matcher(commRate.toString());
			if(!matcher.matches()){
				return Result.error("手续费比例为长度不超过16位数字且最多保留4位小数的有效数字");
			}
			float tem = commRate.floatValue();
			if (!(0 <= tem && tem <= 1)) {
				return Result.error("手续费比例：只能录入大于等于0且小于等于1的数字！");
			}
		}
		
		//1、合作伙伴代理3、个人代理4、总对总代理
		if(!"3".equals(prod2.getAgentType())&&!"4".equals(prod2.getAgentType())){
			//原业务来源为19002-代理或19003-经纪，则代理人代码和代理协议号必填，其他非必填
			if("19002".equals(categoryCode)||"19003".equals(categoryCode)){
				if(StrUtil.isEmpty(agentNo)){
					return Result.error("请输入代理人代码");
				}
				if(StrUtil.isEmpty(protocolNo)){
					return Result.error("请输入代理协议号");
				}
			}
			if(StrUtil.isEmpty(serviceCode)){
				return Result.error("请输入服务代码");
			}
			if(StrUtil.isEmpty(empNo)){
				return Result.error("请输入业务员代码");
			}
			if(StrUtil.isEmpty(teamCode)){
				return Result.error("请输入团队代码");
			}
			if(StrUtil.isEmpty(teamName)){
				return Result.error("请输入团队名称");
			}
		}
		
		//如果投保人编码为空，判断产品投保类型，如果是 1（团单），提示不能为空；如果是 0（个单），判断传入的编码是否为 0，如果为0，同样提示用户生成投保人编码
		if(StrUtil.isEmpty(applicantNo)){
				return Result.error("请选择投保人编码");
		}/*else{
			if("1".equals(appType)){
				if("0".equals(applicantNo)){
					return Result.error("投保人编码不能为空，请至合作伙伴配置页面生成此编码");
				}
			}
		}*/
		TradProdInst prod = new TradProdInst();
		prod.setTradProdCode(tradProdCode);
		TradProdInst newprod = productService.queryTradProdInst(prod);
		
		BigDecimal fpoolRate = null;
		if(!"0".equals(newprod.getPoolType())){
			if(StrUtil.isEmpty(poolInsureCompany)){
				return Result.error("请选择保险公司");
			}
			if(StrUtil.isEmpty(poolProcotol)){
				return Result.error("请选择共保协议");
			}
			if(StrUtil.isEmpty(poolProcotolNo)){
				return Result.error("请输入共保协议号");
			}
			if(StrUtil.isEmpty(poolIssueFlag)){
				return Result.error("请选择出单标志");
			}
			
			if(null != poolAgentRate){
				Pattern pattern = Pattern.compile("([1-9]\\d{0,7}|0)(\\.\\d{1,4})?");  
				Matcher matcher = pattern.matcher(poolAgentRate.toString());
				if(!matcher.matches()){
					return Result.error("代理、经纪费为长度不超过8位数字且最多保留4位小数的有效数字");
				}
			}
				
			if(null != poolRate){
				Pattern pattern = Pattern.compile("[1-9]\\d{0,2}|1000");
		        Matcher matcher = pattern.matcher(poolRate.toString());
		        if(!matcher.matches()){
		        	return Result.error("共保费率请输入1-1000的有效整数");
		        }
	
		        //转换成千分比保存
		        DecimalFormat dfm = new DecimalFormat("#.000");
				Double rate = Double.parseDouble(poolRate.toString());
				if(BigDecimal.ZERO.compareTo(poolRate)==0){
					fpoolRate=new BigDecimal(dfm.format(Double.parseDouble("0")));
				}else{
					Double ratePercent = rate/1000;
					fpoolRate=new BigDecimal(dfm.format(ratePercent));
				}
	
			}
			if(null != poolInsureAmount){
				Pattern pattern = Pattern.compile("([1-9]\\d{0,7}|0)(\\.\\d{1,4})?");  
				Matcher matcher = pattern.matcher(poolInsureAmount.toString());
				if(!matcher.matches()){
					return Result.error("出单费为长度不超过8位数字且最多保留4位小数的有效数字");
				}
			}
			
			if(StrUtil.isEmpty(poolRole)){
				return Result.error("请选择共保角色");
			}
			
		}
		//产品销售类型为代理类型
		if("3".equals(prod2.getAgentType())||"4".equals(prod2.getAgentType())){
			if("1".equals(state)){
				return Result.error("方案添加时，产品销售类型为代理类型则方案不能置为有效状态");
			}
		}
		
		//是否电子保单
		if(StrUtil.isEmpty(isEpolicy)){
			return Result.error("请选择是否电子保单");
		}
		//是否发送电子邮件
		if(StrUtil.isEmpty(EpolicyMali)){
			return Result.error("请选择是否发送电子保单");
		}
		//是否发送电子发票
		
		if(StrUtil.isEmpty(EpolicyInvoice)){
			return Result.error("请选择是否发送电子发票");
		}
		//发送邮件模板
		if(EpolicyMali=="1" && MailTemplate.length()==0){
			return Result.error("请输入邮件模板");
		}
		MailTemplate = URLDecoder.decode(MailTemplate, "UTF-8");
		/*//是否开通支付平台
		if(StrUtil.isEmpty(DredgePay)){
			return Result.error("请选择是否开通支付平台");
		}*/
		
		String ids="";
		if(!StrUtil.isEmpty(selectAccessorylistStr)){
			//创建一个JsonPaser
			JsonParser jsonParser=new JsonParser();
			//通过JsonPaser对象可以把字符串解析成一个JsonElement对象
			JsonElement element=jsonParser.parse(selectAccessorylistStr);
			//把JsonElement转化成jsonArray
			JsonArray jsonArray=null;
			//判断element是不是jsonArray
			if(element.isJsonArray()){
				jsonArray=element.getAsJsonArray();
			}
			//循环得到id的拼接字符串
			for (JsonElement jsonElement : jsonArray) {
				String id=jsonElement.getAsJsonObject().get("id").getAsString();
				ids=ids+id+",";
			}
			//如果长度不为0.去除，
			if(ids.length()>0){
				ids=ids.substring(0, ids.length()-1);
			}					
		}
		
		//是否打印单证,当“是否打印单证”的值为“是”时，单证领用人可输入( "":请选择,"0":是，"1":否)
		if(StrUtil.isEmpty(isPrintCard)){
			return Result.error("是否打印单证不能为空");
		}else{
			if("0".equals(isPrintCard)){
				if(!"3".equals(prod2.getAgentType())&&!"4".equals(prod2.getAgentType())){
					if(StrUtil.isEmpty(cardApplicant)){
						return Result.error("单证领用人不能为空");
					}
				}
			}
		}
		//当“是否发送短信”的值为“是”时，短信模板配置
		if("Y".equals(isMessage)){
			if(StrUtil.isEmpty(messageReceiver)){
				return Result.error("请选择短信接收人");
			}
			if(StrUtil.isEmpty(messageTemplate)){
				return Result.error("短信模板配置不能为空");
			}
		}else{
			messageReceiver="";
		}
		if("Y".equals(isReceipt) && StrUtil.isEmpty(receiptType)){
			return Result.error("回执类型不能为空");
		} 

		/*在 添加 新的投保方案 之前，获取方案表中最大的方案号
		 * 如果为空，则默认从00001开始保存，
		 * 不为空则以当前最大的方案号+1，作为当前新增的方案号
		 */
		
		TradInsuPlan tp = new TradInsuPlan();
		TradInsuPlan tip = gatewayInsureService.getMaxInsuPlanNo(tp);
		if(null==tip){
			tp.setInsuPlanNo("00001");
		}else{
			String maxNo = tip.getInsuPlanNo();
			logger.info("----------------------------------------------------------"+maxNo );
			int nextNoVal = Integer.parseInt(maxNo);
			nextNoVal = nextNoVal+1;
			logger.info("----------------------------------------------------------"+nextNoVal );
			//不足5位，补0
			String nextInsuPlanNo = String.format("%05d", nextNoVal);
			tp.setInsuPlanNo(nextInsuPlanNo);
		}
		tp.setInsuPlanName(insuPlanName);
		tp.setTradProdCode(tradProdCode);
		tp.setPartnerNo(partnerNo);
		tp.setDptCde(dptCde);
		tp.setNewBsnsType(newBsnsType);
		tp.setChannleCode(channleCode);
		tp.setChannleType(channleType);
		tp.setCategoryCode(categoryCode);
		tp.setAgentNo(agentNo);
		tp.setProtocolNo(protocolNo);
		tp.setCommRate(commRate);
		tp.setServiceCode(serviceCode);
		tp.setEmpNo(empNo);
		tp.setTeamCode(teamCode);
		tp.setTeamName(teamName);
		tp.setApplicantNo(applicantNo);
		tp.setIsMessage(isMessage);
		tp.setState(state);
		tp.setSpecialArran(specialArran);
		tp.setIsSeeMoney(isSeeMoney);
		tp.setFileType(fileType);
		tp.setPoolInsureCompany(poolInsureCompany);
		tp.setPoolProcotol(poolProcotol);
		tp.setPoolProcotolNo(poolProcotolNo);
		tp.setPoolIssueFlag(poolIssueFlag);
		tp.setPoolAgentRate(poolAgentRate);
		tp.setPoolRate(fpoolRate);
		tp.setPoolInsureAmount(poolInsureAmount);
		tp.setPoolRole(poolRole);
		
		tp.setIsPrintCard(isPrintCard);
		tp.setCardApplicant(cardApplicant);
		tp.setIsEpolicy(isEpolicy);
		tp.setMessageTemplate(messageTemplate);
		tp.setIsReceipt(isReceipt);
		tp.setMessageReceiver(messageReceiver);
		tp.setCardType(cardType);
		tp.setOperTime(new Date());
		tp.setNotice(reminder);
		tp.setReceiptType(receiptType);
		tp.setEpolicyInvoice(EpolicyInvoice);
		tp.setDredgePay(DredgePay);
		tp.setEpolicyMali(EpolicyMali);
		tp.setMailTemplate(MailTemplate);
		tp.setIdStr(ids);
		tp.setDownloadWay(DownloadWay);
		tp.setCancelReceiver(cancelReceiver);
		tp.setIsCancelMessage(isCancelMessage);
		tp.setCancelTemplate(cancelTemplate);
		boolean flag = gatewayInsureService.addTradInsuPlan(tp);
		//boolean flag = false;
		if(flag){
			logger.info("==========================添加投保方案成功=============================");

			//根据方案对应的产品的产品类型，查询相应方案组信息,将该方案和方案组信息维护到方案与方案组关联表
			TradProdInst tradProdInst=new TradProdInst();
			tradProdInst.setTradProdCode(tradProdCode);
			tradProdInst=productService.queryTradProdInst(tradProdInst);//得到产品类型
			
			//根据产品类型得到方案组ID
			TradPlanGroup gp = new TradPlanGroup();
			gp.setProdType(tradProdInst.getTradProdType());
			TradPlanGroup pg = plangroupService.queryTradPlanGroupID(gp);
			
			//维护方案与方案组关联表
			if(pg!=null){
				TradInsuPlanGroup group = new TradInsuPlanGroup();
				group.setInsuPlanNumber(tp.getInsuPlanNo());
				group.setPlanGroupId(StrUtil.getVal(pg.getGroupId()));
				group.setRequired("0");
				boolean f = insuPlanGroupService.addTradInsuPlanGroup(group);
				if(!f){return Result.error("维护方案与方案组关联出错");}
			}
			Map<String,String>  resultMap =new  HashMap<String,String>();
			resultMap.put("InsuPlanNo", tp.getInsuPlanNo());
			resultMap.put("AgentType", prod2.getAgentType());
			return Result.successAndData("添加成功",resultMap);
		}else{
			logger.info("==========================添加投保方案失败=============================");
			return Result.error("添加失败");
		}
	}
	
	
	
	/**
	 * 删除投保方案，只能删除 无效 状态数据，同时，需要删除方案与方案组的关联
	 * @param tp
	 * @param insuPlanNo
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/delInsuPlan")
	public @ResponseBody Result deleteTradInsuPlan(TradInsuPlan tp,String insuPlanNo,String channelCode) throws Exception{
		if(StrUtil.isEmpty(insuPlanNo)){
			return Result.error("投保方案号不能为空");
		}else{
			tp.setInsuPlanNo(insuPlanNo);
			tp.setPartnerNo(channelCode);
			TradInsuPlan tradInsuPlan = gatewayInsureService.queryTradInsuPlanInfo(tp);
			String status = tradInsuPlan.getState();
			if(1==Integer.parseInt(status)){
				return Result.error("该方案状态为有效，不能删除");
			}else{
				boolean flag = gatewayInsureService.delTradInsuPlan(tp);
				if(flag){
					//删除方案组关联
					insuPlanGroupService.deleteTradInsuPlanGroupByInsuPlanNo(insuPlanNo);
					return Result.success("删除成功");
				}else{
					return Result.error("删除失败");
				}
			}
		}
	}
	
	
	/**
	 * 加载 投保方案信息
	 * @param tp
	 * @param insuPlanNo
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("null")
	@RequestMapping(value = "/loadInsuPlanInfo")
	public @ResponseBody String queryInsuPlanInfo(TradInsuPlan tp,String insuPlanNo) throws Exception{
			tp.setInsuPlanNo(insuPlanNo);
			Map<String,Object> map= gatewayInsureService.queryMapTradInsuPlanInfo(tp);
			String agentType= (String) map.get("AGENTTYPE");
			String isEpolicyMali=(String) map.get("EPOLICYMALI");
			//承保短信模板
			String messageTemplate = (String) map.get("MESSAGETEMPLATE");
			if(!"".equals(messageTemplate) && null != messageTemplate){
				String messageTemplate_val = (tradSmsTemplateService.queryTradeByCode(messageTemplate)).getSmsTemplateText();
				map.put("messageTemplate_val", messageTemplate_val);
			}
			//注销短信模板
			String cancelTemplate = (String) map.get("CANCELTEMPLATE");
			if(!"".equals(cancelTemplate) && null != cancelTemplate){
				String cancelTemplate_val = (tradSmsTemplateService.queryTradeByCode(cancelTemplate)).getSmsTemplateText();
				map.put("cancelTemplate_val", cancelTemplate_val);
			}
			if(isEpolicyMali==null){
				isEpolicyMali="2";
			}
			map.put("EPOLICYMALI", isEpolicyMali);
			String isEpolicy=(String) map.get("ISEPOLICY");
			if(isEpolicy==null){
				isEpolicy="S";
			}
			map.put("ISEPOLICY", isEpolicy);
			String idStr=(String) map.get("IDSTR");
			String[] ids=null;
			if(idStr!=null){
				ids=idStr.split(",");
			}
			//“附件发送类型”列表
			List<DictDto> Accessorylist=DictCache.getDict("acc_type");
			map.put("Accessorylist", Accessorylist);
			map.put("ids", ids);
			if("3".equals(agentType)||"4".equals(agentType)){
				List<Map> list = this.gatewayInsureService.queryTradAgentInfoByInsuPlanNo(insuPlanNo);
				if(!list.isEmpty()){
					List<Map> list1= new ArrayList<Map>();
					for (Map map2 : list) {
						Map<String,String> newmap = new HashMap<String,String>();
						String id = map2.get("ID")+"";
						String cardapplicant = map2.get("CARDAPPLICANT")+"";
						String value = map2.get("COMMRATE")+"";
						newmap.put("id", id);
						newmap.put("cardapplicant", cardapplicant);
						newmap.put("value", value);
						list1.add(newmap);
						map.put("map", list1);
					}
				}
			}
			String jsonStr = JsonUtils.toJson(map);
			return jsonStr;
		}
	
	
	/**
	 * 修改方案信息
	 * @param insuPlanNo
	 * @param insuPlanName
	 * @param tradProdCode
	 * @param partnerNo
	 * @param agentNo
	 * @param protocolNo
	 * @param commRate
	 * @param serviceCode
	 * @param empNo
	 * @param teamCode
	 * @param teamName
	 * @param applicantNo
	 * @param isMessage
	 * @param channleCode
	 * @param channleType
	 * @param newBsnsType
	 * @param categoryCode
	 * @param endDate
	 * @param dptCde
	 * @param specialArran
	 * @param state
	 * @param isSeeMoney
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/updateInsuPlanInfo")
	public @ResponseBody Result updateInsuPlanInfo(HttpSession session,String fileType,String insuPlanNo,String insuPlanName,String tradProdCode,String partnerNo,String agentNo,String protocolNo,
			BigDecimal commRate,String serviceCode,String empNo,String teamCode,String teamName,String applicantNo,String isMessage,String channleCode,String channleType,String newBsnsType,
			String categoryCode,String endDate,String dptCde,String specialArran,String state,String isSeeMoney,String poolInsureCompany,String poolProcotol,
			String poolProcotolNo,String poolIssueFlag,BigDecimal poolAgentRate,BigDecimal poolRate,BigDecimal poolInsureAmount,String poolRole,
			String isPrintCard,String cardApplicant,String isEpolicy,String messageTemplate,String isReceipt,String messageReceiver,String cardType,String reminder,String receiptType,
			String EpolicyInvoice, String DredgePay,String EpolicyMali,String MailTemplate ,String selectAccessorylistStr,String DownloadWay,String isCancelMessage,String cancelReceiver,String cancelTemplate) throws Exception{

		
		cancelTemplate=URLDecoder.decode(cancelTemplate, "UTF-8");
		//首先进行非空、格式校验
		if(StrUtil.isEmpty(insuPlanName)){
			return Result.error("请输入投保方案名称");
		}
		if(StrUtil.isEmpty(tradProdCode)){
			return Result.error("请选择产品编号");
		}
		
		//获取产品的投保类型：0 代表个单；1代表 团单
		TradProdInst prod1 = new TradProdInst();
		prod1.setTradProdCode(tradProdCode);
		TradProdInst prod2 = productService.queryTradProdInst(prod1);
		String appType = prod2.getTradAppType();

		if(StrUtil.isEmpty(partnerNo)){
			return Result.error("请选择合作伙伴代码");
		}
		
		//1、合作伙伴代理3、个人代理4、总对总代理
		if(!"3".equals(prod2.getAgentType())&&!"4".equals(prod2.getAgentType())){
			if(StrUtil.isEmpty(channleCode)){
				return Result.error("请选择归属渠道");
			}
			if(StrUtil.isEmpty(channleType)){
				return Result.error("请选择渠道类型");
			}
			if(StrUtil.isEmpty(newBsnsType)){
				return Result.error("请选择新业务来源");
			}
			if(StrUtil.isEmpty(categoryCode)){
				return Result.error("请选择原业务来源");
			}
			if(StrUtil.isEmpty(dptCde)){
				return Result.error("请选择出单机构");
			}
		}
		if(null == commRate){
			return Result.error("请输入手续费比例");
		}else{
			Pattern pattern = Pattern.compile("([1-9]\\d{0,15}|0)(\\.\\d{1,4})?");  
			Matcher matcher = pattern.matcher(commRate.toString());
			if(!matcher.matches()){
				return Result.error("手续费比例为长度不超过16位数字且最多保留4位小数的有效数字");
			}
			float tem = commRate.floatValue();
			if (!(0 <= tem && tem <= 1)) {
				return Result.error("手续费比例：只能录入大于等于0且小于等于1的数字！");
			}
		}
		//1、合作伙伴代理3、个人代理4、总对总代理
		if(!"3".equals(prod2.getAgentType())&&!"4".equals(prod2.getAgentType())){
			//原业务来源为19002-代理或19003-经纪，则代理人代码和代理协议号必填，其他非必填
			if("19002".equals(categoryCode)||"19003".equals(categoryCode)){
				if(StrUtil.isEmpty(agentNo)){
					return Result.error("请输入代理人代码");
				}
				if(StrUtil.isEmpty(protocolNo)){
					return Result.error("请输入代理协议号");
				}
			}
			if(StrUtil.isEmpty(serviceCode)){
				return Result.error("请输入服务代码");
			}
			if(StrUtil.isEmpty(empNo)){
				return Result.error("请输入业务员代码");
			}
			if(StrUtil.isEmpty(teamCode)){
				return Result.error("请输入团队代码");
			}
			if(StrUtil.isEmpty(teamName)){
				return Result.error("请输入团队名称");
			}
		}
		
		//如果投保人编码为空，提示；不为空，判断产品投保类型，如果是 1（团单），提示不能为空；如果是 0（个单），判断传入的编码是否为 0，如果为0，同样提示用户生成投保人编码
		if(StrUtil.isEmpty(applicantNo)){
				return Result.error("请选择投保人编码");
		}/*else{
			if("1".equals(appType)){
				if("0".equals(applicantNo)){
					return Result.error("投保人编码不能为空，请至合租伙伴配置页面生成次编码");
				}
			}
		}*/
		
		//产品销售类型为代理类型
		if("3".equals(prod2.getAgentType())||"4".equals(prod2.getAgentType())){
			if("1".equals(state)){
				if(gatewayInsureService.proxyInfoIsEmpty(insuPlanNo)){
					return Result.error("代理信息为空 时不能将方案状态置为有效,请配置代理信息");
				}
			}
		}
		
		//是否发送电子邮件
		if(StrUtil.isEmpty(EpolicyMali)){
			return Result.error("请选择是否发送电子保单");
		}
		//是否发送电子发票
		
		if(StrUtil.isEmpty(EpolicyInvoice)){
			return Result.error("请选择是否发送电子发票");
		}
		//发送邮件模板
		if(EpolicyMali=="1" && MailTemplate.length()==0){
			return Result.error("请输入邮件模板");
		}
		MailTemplate = URLDecoder.decode(MailTemplate, "UTF-8");
		/*//是否开通支付平台
		if(StrUtil.isEmpty(DredgePay)){
			return Result.error("请选择是否开通支付平台");
		}*/
		
		String ids="";
		if(!StrUtil.isEmpty(selectAccessorylistStr)){
			//创建一个JsonPaser
			JsonParser jsonParser=new JsonParser();
			//通过JsonPaser对象可以把字符串解析成一个JsonElement对象
			JsonElement element=jsonParser.parse(selectAccessorylistStr);
			//把JsonElement转化成jsonArray
			JsonArray jsonArray=null;
			//判断element是不是jsonArray
			if(element.isJsonArray()){
				jsonArray=element.getAsJsonArray();
			}
			//循环得到id的拼接字符串
			for (JsonElement jsonElement : jsonArray) {
				String id=jsonElement.getAsJsonObject().get("id").getAsString();
				ids=ids+id+",";
			}
			//如果长度不为0.去除，
			if(ids.length()>0){
				ids=ids.substring(0, ids.length()-1);
			}					
		}							
		//是否打印单证,当“是否打印单证”的值为“是”时，单证领用人可输入( "":请选择,"0":是，"1":否)
		if(StrUtil.isEmpty(isPrintCard)){
			return Result.error("是否打印单证不能为空");
		}else{
			if("0".equals(isPrintCard)){
				if(StrUtil.isEmpty(cardType)){
					return Result.error("单证类型不能为空");
				}
				if(!"3".equals(prod2.getAgentType())&&!"4".equals(prod2.getAgentType())){
					if(StrUtil.isEmpty(cardApplicant)){
						return Result.error("单证领用人不能为空");
					}
				}
			}
		}
		//当“是否发送短信”的值为“是”时，短信模板配置
		if("Y".equals(isMessage)){
			if(StrUtil.isEmpty(messageReceiver)){
				return Result.error("请选择短信接收人");
			}
			if(StrUtil.isEmpty(messageTemplate)){
				return Result.error("短信模板配置不能为空");
			}
		}else{
			messageReceiver="";
		}
		
		
		TradProdInst prod = new TradProdInst();
		prod.setTradProdCode(tradProdCode);
		TradProdInst newprod = productService.queryTradProdInst(prod);
		
		BigDecimal fpoolRate = null;
		if(!"0".equals(newprod.getPoolType())){
		
			if(StrUtil.isEmpty(poolInsureCompany)){
				return Result.error("请选择保险公司");
			}
			if(StrUtil.isEmpty(poolProcotol)){
				return Result.error("请选择共保协议");
			}
			if(StrUtil.isEmpty(poolProcotolNo)){
				return Result.error("请输入共保协议号");
			}
			if(StrUtil.isEmpty(poolIssueFlag)){
				return Result.error("请选择出单标志");
			}
			
			if(null != poolAgentRate){
				Pattern pattern = Pattern.compile("([1-9]\\d{0,7}|0)(\\.\\d{1,4})?");  
				Matcher matcher = pattern.matcher(poolAgentRate.toString());
				if(!matcher.matches()){
					return Result.error("代理、经纪费为长度不超过8位数字且最多保留4位小数的有效数字");
				}
			}
				
			if(null != poolRate){
				Pattern pattern = Pattern.compile("[1-9]\\d{0,2}|1000");
		        Matcher matcher = pattern.matcher(poolRate.toString());
		        if(!matcher.matches()){
		        	return Result.error("共保费率请输入1-1000的有效整数");
		        }
	
		        //转换成千分比保存
		        DecimalFormat dfm = new DecimalFormat("#.000");
				Double rate = Double.parseDouble(poolRate.toString());
				if(BigDecimal.ZERO.compareTo(poolRate)==0){
					fpoolRate=new BigDecimal(dfm.format(Double.parseDouble("0")));
				}else{
					Double ratePercent = rate/1000;
					fpoolRate=new BigDecimal(dfm.format(ratePercent));
				}
			}
			
			if(null != poolInsureAmount){
				Pattern pattern = Pattern.compile("([1-9]\\d{0,7}|0)(\\.\\d{1,4})?");  
				Matcher matcher = pattern.matcher(poolInsureAmount.toString());
				if(!matcher.matches()){
					return Result.error("出单费为长度不超过8位数字且最多保留4位小数的有效数字");
				}
			}
			
			if(StrUtil.isEmpty(poolRole)){
				return Result.error("请选择共保角色");
			}
			
		}if("Y".equals(isReceipt) && StrUtil.isEmpty(receiptType)){
			return Result.error("回执类型不能为空");
		}

		TradInsuPlan tp = new TradInsuPlan();
		tp.setInsuPlanNo(insuPlanNo);
		tp.setInsuPlanName(insuPlanName);
		tp.setTradProdCode(tradProdCode);
		tp.setPartnerNo(partnerNo);
		tp.setDptCde(dptCde);
		tp.setNewBsnsType(newBsnsType);
		tp.setCategoryCode(categoryCode);
		tp.setChannleCode(channleCode);
		tp.setChannleType(channleType);
		tp.setAgentNo(agentNo);
		tp.setProtocolNo(protocolNo);
		tp.setCommRate(commRate);
		tp.setServiceCode(serviceCode);
		tp.setEmpNo(empNo);
		tp.setTeamCode(teamCode);
		tp.setTeamName(teamName);
		tp.setApplicantNo(applicantNo);
		tp.setIsMessage(isMessage);
		tp.setState(state);
		tp.setSpecialArran(specialArran);
		tp.setIsSeeMoney(isSeeMoney);
		
		tp.setPoolInsureCompany(poolInsureCompany);
		tp.setPoolProcotol(poolProcotol);
		tp.setPoolProcotolNo(poolProcotolNo);
		tp.setPoolIssueFlag(poolIssueFlag);
		tp.setPoolAgentRate(poolAgentRate);
		tp.setPoolRate(fpoolRate);
		tp.setPoolInsureAmount(poolInsureAmount);
		tp.setPoolRole(poolRole);
		tp.setFileType(fileType);
		tp.setIsPrintCard(isPrintCard);
		tp.setCardApplicant(cardApplicant);
		tp.setIsEpolicy(isEpolicy);
		tp.setMessageTemplate(messageTemplate);
		tp.setIsReceipt(isReceipt);
		tp.setMessageReceiver(messageReceiver);
		tp.setCardType(cardType);
		tp.setOperTime(new Date());
		tp.setNotice(reminder);
		tp.setReceiptType(receiptType);
		tp.setEpolicyInvoice(EpolicyInvoice);
		tp.setDredgePay(DredgePay);
		tp.setEpolicyMali(EpolicyMali);
		tp.setMailTemplate(MailTemplate);
		tp.setIdStr(ids);
		tp.setDownloadWay(DownloadWay);
		tp.setCancelReceiver(cancelReceiver);
		tp.setIsCancelMessage(isCancelMessage);
		tp.setCancelTemplate(cancelTemplate);

		//如果此方案修改了产品，则同步更改方案与方案组关联，否则不做修改
		TradInsuPlan updateBefore = new TradInsuPlan();
		updateBefore.setInsuPlanNo(insuPlanNo);
		TradInsuPlan oldTradInsuPlan = gatewayInsureService.queryTradInsuPlanInfo(updateBefore);
		if(!oldTradInsuPlan.getTradProdCode().equals(tradProdCode)){
			//根据方案对应的产品的产品类型，查询相应方案组信息,将该方案和方案组信息维护到方案组表
			TradProdInst tradProdInst=new TradProdInst();
			tradProdInst.setTradProdCode(tradProdCode);
			tradProdInst=productService.queryTradProdInst(tradProdInst);//得到产品类型
			
			//根据产品类型得到方案组ID
			TradPlanGroup gp = new TradPlanGroup();
			gp.setProdType(tradProdInst.getTradProdType());
			TradPlanGroup pg = plangroupService.queryTradPlanGroupID(gp);
			
			//维护方案与方案组关联表
			if(pg!=null){
				TradInsuPlanGroup group = new TradInsuPlanGroup();
				group.setInsuPlanNumber(tp.getInsuPlanNo());
				group.setPlanGroupId(StrUtil.getVal(pg.getGroupId()));
				boolean f = insuPlanGroupService.updateTradInsuPlanGroup(group);
				if(!f){return Result.error("维护方案与方案组关联出错");}
			}
		}
		
		boolean flag = gatewayInsureService.updateTradInsuPlanInfo(tp);
		
		if(flag){
			logger.info("==========================修改投保方案成功=============================");
			
			return Result.success("修改成功");
		}else{
			logger.info("==========================修改投保方案失败=============================");
			return Result.error("修改失败");
		}
	}
	
	
	
	// 归属渠道-渠道类型-新业务来源处理
	@RequestMapping(value = "/loadSubDropList")
	public @ResponseBody List<DictDto> getSubDropListData(String codeType, String parentCode) throws Exception {
		List<DictDto> list = new ArrayList<DictDto>();
		if (StrUtil.isNotEmpty(codeType) && StrUtil.isNotEmpty(parentCode)) {
			List<DictDto> subDataList = DictCache.getDictDataByParentCode(codeType, parentCode);
			//复制list
			list.addAll(subDataList);
			//倒序
			Collections.reverse(list);
			DictDto dd = new DictDto();
			dd.setCode("");
			dd.setCodeName("----请选择----");
			list.add(dd);
			//倒序
			Collections.reverse(list);
			return list;
		}else{
			DictDto dd = new DictDto();
			dd.setCode("");
			if("channel_type".equals(codeType)){
				dd.setCodeName("----请选择归属渠道----");
			}else if("new_business_source".equals(codeType)){
				dd.setCodeName("----请选择渠道类型----");
			}
			list.add(dd);
		}
		return list;
	}
	
	//选取旧业务来源
	@RequestMapping(value = "/chooseBsnsType")
	public @ResponseBody DictDto chooseBsnsType(String parentCode,String newBsnsCode) throws Exception {
		DictDto dd = new DictDto();
		if (StrUtil.isNotEmpty(parentCode)&&StrUtil.isNotEmpty(newBsnsCode)) {
			List<DictDto> subDataList = DictCache.getDictDataByParentCode("new_business_source", parentCode);
			for (DictDto dictDto : subDataList) {
				if(newBsnsCode.equals(dictDto.getCode())){
					return dictDto;
				}
			}
		}else{
			dd.setOtherCode("");
		}
		return dd;
	}
	
	@RequestMapping(value = "/loadConfProxyInfo")
	public @ResponseBody Page loadConfProxyInfo(Integer size,Integer pageIndex,String channelCode,String agentType,
			String confStatus,String userName,String userCode,String insuPlanNo,
			String branch,String branchName) throws Exception{
		Page<TradAgentInfo> page=new Page<TradAgentInfo>();
		page.setCurrent(pageIndex);
		page.setSize(size);
		TradAgentInfo tradAgentInfo=new TradAgentInfo();
		tradAgentInfo.setAgentType(agentType);
		tradAgentInfo.setUserCode(userCode);
		page.setType(tradAgentInfo);
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("channelCode", channelCode);//机构代码
		map.put("userName", userName);//代理人名称
		map.put("confStatus", confStatus);//配置状态
		map.put("insuPlanNo", insuPlanNo);
		map.put("branch", branch);//网点
		map.put("branchName", branchName);//网点名称
		
		Page page2=gatewayInsureService.queryPageForTradAgentInfo(page, map);
		return page2;
	}
	@RequestMapping(value = "/loadConfProxyInfoEdit")
	public @ResponseBody Page loadConfProxyInfoEdit(Integer size,Integer pageIndex,String insuPlanNo,String agentType) throws Exception{
		Page page=new Page();
		page.setCurrent(pageIndex);
		page.setSize(size);
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("insuPlanNo", insuPlanNo);
		map.put("agentType", agentType);
		Page page2=gatewayInsureService.queryPageForTradAgentInfoEdit(page, map);
		return page2;
	}
	
	/**
	 * 添加/修改代理信息
	 * @param session
	 * @param insuPlanNo
	 * @param agentTypeList
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/updateProxyInfo")
	public @ResponseBody Result updateProxyInfo(HttpSession session,String insuPlanNo,String isPrintCard,String agentTypeList) throws Exception{
		if(StrUtil.isEmpty(insuPlanNo)){
			return Result.error("方案号不能为空");
		}
		if(StrUtil.isEmpty(agentTypeList)){
			return Result.error("代理信息不能为空");
		}
		if("0".equals(isPrintCard)){//( "":请选择,"0":是，"1":否)
			//创建一个JsonParser
			JsonParser parser = new JsonParser();
			//通过JsonParser对象可以把json格式的字符串解析成一个JsonElement对象
			JsonElement el = parser.parse(agentTypeList);
			//把JsonElement对象转换成JsonArray
			JsonArray jsonArray = null;
			if(el.isJsonArray()){
				jsonArray = el.getAsJsonArray();
			}else{
				return Result.error("无效的代理信息");
			}
			for (JsonElement jsonElement : jsonArray) {
				String id =jsonElement.getAsJsonObject().get("id").getAsString();
				String cardapplicant=jsonElement.getAsJsonObject().get("cardapplicant").getAsString();
				if(StrUtil.isEmpty(id)||StrUtil.isEmpty(cardapplicant)){
					return Result.error("您配置的代理信息中存在单证领用人为空的,单证领用人不能为空");
				}
			}
		}
		GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		
		boolean flag = gatewayInsureService.updateProxyInfo(insuPlanNo, gatewayuser, agentTypeList);
		if(flag){
			return Result.success("更新成功");
		}else{
			return Result.error("更新失败");
		}
	}
	
	
	@RequestMapping(value = "/copyAddTradInsuPlan")
	public @ResponseBody Result copyAddTradInsuPlan(HttpSession session,String insuPlanName,String tradProdCode,String partnerNo,String agentNo,String protocolNo,
			BigDecimal commRate,String serviceCode,String empNo,String teamCode,String teamName,String applicantNo,String isMessage,String channleCode,String channleType,String newBsnsType,
			String categoryCode,String endDate,String dptCde,String specialArran,String state,String isSeeMoney,String poolInsureCompany,String poolProcotol,
			String poolProcotolNo,String poolIssueFlag,BigDecimal poolAgentRate,BigDecimal poolRate,BigDecimal poolInsureAmount,String poolRole,
			String isPrintCard,String cardApplicant,String isEpolicy,String messageTemplate,String isReceipt,String messageReceiver,String cardType,
			String oldPlanNo,String oldAgentType,String reminder,String receiptType,
			String EpolicyInvoice, String DredgePay,String EpolicyMali,String MailTemplate ,String selectAccessorylistStr,String DownloadWay,String isCancelMessage,String cancelReceiver,String cancelTemplate) throws Exception{
		cancelTemplate=URLDecoder.decode(cancelTemplate, "UTF-8");
		boolean isCopy = false;//是否复制代理信息 标志
		TradInsuPlan plan = new TradInsuPlan();
		plan.setInsuPlanNo(oldPlanNo);		
		TradInsuPlan oldInsuPlan =  gatewayInsureService.queryTradInsuPlanInfo(plan);//被复制的方案
		//首先进行非空、格式校验
		if(StrUtil.isEmpty(insuPlanName)){
			return Result.error("请输入投保方案名称");
		}
		if(StrUtil.isEmpty(tradProdCode)){
			return Result.error("请选择产品编号");
		}
		
		//获取产品的投保类型：0 代表个单；1代表 团单
		TradProdInst prod1 = new TradProdInst();
		prod1.setTradProdCode(tradProdCode);
		TradProdInst prod2 = productService.queryTradProdInst(prod1);
		String appType = prod2.getTradAppType();
		//如果产品类型与原类型相同并且 合作伙伴代码与原合作伙伴代码相同
		if(prod2.getAgentType().equals(oldAgentType)&&oldInsuPlan.getPartnerNo().equals(partnerNo)){
			isCopy = true;
		}
		
		if(StrUtil.isEmpty(partnerNo)){
			return Result.error("请选择合作伙伴代码");
		}
		
		//1、合作伙伴代理3、个人代理4、总对总代理
		if(!"3".equals(prod2.getAgentType())&&!"4".equals(prod2.getAgentType())){
			if(StrUtil.isEmpty(channleCode)){
				return Result.error("请选择归属渠道");
			}
			if(StrUtil.isEmpty(channleType)){
				return Result.error("请选择渠道类型");
			}
			if(StrUtil.isEmpty(newBsnsType)){
				return Result.error("请选择新业务来源");
			}
			if(StrUtil.isEmpty(categoryCode)){
				return Result.error("请选择原业务来源");
			}
			if(StrUtil.isEmpty(dptCde)){
				return Result.error("请选择出单机构");
			}
		}
		
		if(null == commRate){
			return Result.error("请输入手续费比例");
		}else{
			Pattern pattern = Pattern.compile("([1-9]\\d{0,15}|0)(\\.\\d{1,4})?");  
			Matcher matcher = pattern.matcher(commRate.toString());
			if(!matcher.matches()){
				return Result.error("手续费比例为长度不超过16位数字且最多保留4位小数的有效数字");
			}
			float tem = commRate.floatValue();
			if (!(0 <= tem && tem <= 1)) {
				return Result.error("手续费比例：只能录入大于等于0且小于等于1的数字！");
			}
		}			
		//1、合作伙伴代理3、个人代理4、总对总代理
		if(!"3".equals(prod2.getAgentType())&&!"4".equals(prod2.getAgentType())){
			//原业务来源为19002-代理或19003-经纪，则代理人代码和代理协议号必填，其他非必填
			if("19002".equals(categoryCode)||"19003".equals(categoryCode)){
				if(StrUtil.isEmpty(agentNo)){
					return Result.error("请输入代理人代码");
				}
				if(StrUtil.isEmpty(protocolNo)){
					return Result.error("请输入代理协议号");
				}
			}
			if(StrUtil.isEmpty(serviceCode)){
				return Result.error("请输入服务代码");
			}
			if(StrUtil.isEmpty(empNo)){
				return Result.error("请输入业务员代码");
			}
			if(StrUtil.isEmpty(teamCode)){
				return Result.error("请输入团队代码");
			}
			if(StrUtil.isEmpty(teamName)){
				return Result.error("请输入团队名称");
			}
		}
		
		//如果投保人编码为空，判断产品投保类型，如果是 1（团单），提示不能为空；如果是 0（个单），判断传入的编码是否为 0，如果为0，同样提示用户生成投保人编码
		if(StrUtil.isEmpty(applicantNo)){
				return Result.error("请选择投保人编码");
		}/*else{
			if("1".equals(appType)){
				if("0".equals(applicantNo)){
					return Result.error("投保人编码不能为空，请至合作伙伴配置页面生成此编码");
				}
			}
		}*/
		TradProdInst prod = new TradProdInst();
		prod.setTradProdCode(tradProdCode);
		TradProdInst newprod = productService.queryTradProdInst(prod);
		
		BigDecimal fpoolRate = null;
		if(!"0".equals(newprod.getPoolType())){
			if(StrUtil.isEmpty(poolInsureCompany)){
				return Result.error("请选择保险公司");
			}
			if(StrUtil.isEmpty(poolProcotol)){
				return Result.error("请选择共保协议");
			}
			if(StrUtil.isEmpty(poolProcotolNo)){
				return Result.error("请输入共保协议号");
			}
			if(StrUtil.isEmpty(poolIssueFlag)){
				return Result.error("请选择出单标志");
			}
			
			if(null != poolAgentRate){
				Pattern pattern = Pattern.compile("([1-9]\\d{0,7}|0)(\\.\\d{1,4})?");  
				Matcher matcher = pattern.matcher(poolAgentRate.toString());
				if(!matcher.matches()){
					return Result.error("代理、经纪费为长度不超过8位数字且最多保留4位小数的有效数字");
				}
			}
				
			if(null != poolRate){
				Pattern pattern = Pattern.compile("[1-9]\\d{0,2}|1000");
		        Matcher matcher = pattern.matcher(poolRate.toString());
		        if(!matcher.matches()){
		        	return Result.error("共保费率请输入1-1000的有效整数");
		        }
	
		        //转换成千分比保存
		        DecimalFormat dfm = new DecimalFormat("#.000");
				Double rate = Double.parseDouble(poolRate.toString());
				if(BigDecimal.ZERO.compareTo(poolRate)==0){
					fpoolRate=new BigDecimal(dfm.format(Double.parseDouble("0")));
				}else{
					Double ratePercent = rate/1000;
					fpoolRate=new BigDecimal(dfm.format(ratePercent));
				}
	
			}
			if(null != poolInsureAmount){
				Pattern pattern = Pattern.compile("([1-9]\\d{0,7}|0)(\\.\\d{1,4})?");  
				Matcher matcher = pattern.matcher(poolInsureAmount.toString());
				if(!matcher.matches()){
					return Result.error("出单费为长度不超过8位数字且最多保留4位小数的有效数字");
				}
			}
			
			if(StrUtil.isEmpty(poolRole)){
				return Result.error("请选择共保角色");
			}
			
		}
		
		//产品销售类型为代理类型
		if("3".equals(prod2.getAgentType())||"4".equals(prod2.getAgentType())){
			if(prod2.getAgentType().equals(oldAgentType)&&oldInsuPlan.getPartnerNo().equals(partnerNo)){
				if("1".equals(state)){
					if(gatewayInsureService.proxyInfoIsEmpty(oldPlanNo)){
						return Result.error("原方案未配置代理信息,该方案不能置为有效");
					}
				}
			}else{
				if("1".equals(state)){
					return Result.error("产品销售类型更改或合作伙伴更改,该方案不能置为有效");
				}
			}
		}
		//是否发送电子邮件
		if(StrUtil.isEmpty(EpolicyMali)){
			return Result.error("请选择是否发送电子保单");
		}
		//是否发送电子发票
		
		if(StrUtil.isEmpty(EpolicyInvoice)){
			return Result.error("请选择是否发送电子发票");
		}
		//发送邮件模板
		if(EpolicyMali=="1" && MailTemplate.length()==0){
			return Result.error("请输入邮件模板");
		}
		MailTemplate = URLDecoder.decode(MailTemplate, "UTF-8");
		/*//是否开通支付平台
		if(StrUtil.isEmpty(DredgePay)){
			return Result.error("请选择是否开通支付平台");
		}*/
		
		String ids="";
		if(!StrUtil.isEmpty(selectAccessorylistStr)){
			//创建一个JsonPaser
			JsonParser jsonParser=new JsonParser();
			//通过JsonPaser对象可以把字符串解析成一个JsonElement对象
			JsonElement element=jsonParser.parse(selectAccessorylistStr);
			//把JsonElement转化成jsonArray
			JsonArray jsonArray=null;
			//判断element是不是jsonArray
			if(element.isJsonArray()){
				jsonArray=element.getAsJsonArray();
			}
			//循环得到id的拼接字符串
			for (JsonElement jsonElement : jsonArray) {
				String id=jsonElement.getAsJsonObject().get("id").getAsString();
				ids=ids+id+",";
			}
			//如果长度不为0.去除，
			if(ids.length()>0){
				ids=ids.substring(0, ids.length()-1);
			}					
		}					
		//是否打印单证,当“是否打印单证”的值为“是”时，单证领用人可输入( "":请选择,"0":是，"1":否)
		if(StrUtil.isEmpty(isPrintCard)){
			return Result.error("是否打印单证不能为空");
		}else{
			if("0".equals(isPrintCard)){
				if(!"3".equals(prod2.getAgentType())&&!"4".equals(prod2.getAgentType())){
					if(StrUtil.isEmpty(cardApplicant)){
						return Result.error("单证领用人不能为空");
					}
				}
			}
		}
		//当“是否发送短信”的值为“是”时，短信模板配置
		if("Y".equals(isMessage)){
			if(StrUtil.isEmpty(messageReceiver)){
				return Result.error("请选择短信接收人");
			}
			if(StrUtil.isEmpty(messageTemplate)){
				return Result.error("短信模板配置不能为空");
			}
		}else{
			messageReceiver="";
		}if("Y".equals(isReceipt) && StrUtil.isEmpty(receiptType)){
			return Result.error("回执类型不能为空");
		}

		/*在 添加 新的投保方案 之前，获取方案表中最大的方案号
		 * 如果为空，则默认从00001开始保存，
		 * 不为空则以当前最大的方案号+1，作为当前新增的方案号
		 */
			
		TradInsuPlan tp = new TradInsuPlan();
		TradInsuPlan tip = gatewayInsureService.getMaxInsuPlanNo(tp);
		if(null==tip){
			tp.setInsuPlanNo("00001");
		}else{
			String maxNo = tip.getInsuPlanNo();
			logger.info("----------------------------------------------------------"+maxNo );
			int nextNoVal = Integer.parseInt(maxNo);
			nextNoVal = nextNoVal+1;
			logger.info("----------------------------------------------------------"+nextNoVal );
			//不足5位，补0
			String nextInsuPlanNo = String.format("%05d", nextNoVal);
			tp.setInsuPlanNo(nextInsuPlanNo);
		}
		tp.setInsuPlanName(insuPlanName);
		tp.setTradProdCode(tradProdCode);
		tp.setPartnerNo(partnerNo);
		tp.setDptCde(dptCde);
		tp.setNewBsnsType(newBsnsType);
		tp.setChannleCode(channleCode);
		tp.setChannleType(channleType);
		tp.setCategoryCode(categoryCode);
		tp.setAgentNo(agentNo);
		tp.setProtocolNo(protocolNo);
		tp.setCommRate(commRate);
		tp.setServiceCode(serviceCode);
		tp.setEmpNo(empNo);
		tp.setTeamCode(teamCode);
		tp.setTeamName(teamName);
		tp.setApplicantNo(applicantNo);
		tp.setIsMessage(isMessage);
		tp.setState(state);
		tp.setSpecialArran(specialArran);
		tp.setIsSeeMoney(isSeeMoney);
		
		tp.setPoolInsureCompany(poolInsureCompany);
		tp.setPoolProcotol(poolProcotol);
		tp.setPoolProcotolNo(poolProcotolNo);
		tp.setPoolIssueFlag(poolIssueFlag);
		tp.setPoolAgentRate(poolAgentRate);
		tp.setPoolRate(fpoolRate);
		tp.setPoolInsureAmount(poolInsureAmount);
		tp.setPoolRole(poolRole);
		
		tp.setIsPrintCard(isPrintCard);
		tp.setCardApplicant(cardApplicant);
		tp.setIsEpolicy(isEpolicy);
		tp.setMessageTemplate(messageTemplate);
		tp.setIsReceipt(isReceipt);
		tp.setMessageReceiver(messageReceiver);
		tp.setCardType(cardType);
		tp.setOperTime(new Date());
		tp.setNotice(reminder);
		tp.setReceiptType(receiptType);
		tp.setEpolicyInvoice(EpolicyInvoice);
		tp.setDredgePay(DredgePay);
		tp.setEpolicyMali(EpolicyMali);
		tp.setMailTemplate(MailTemplate);
		tp.setIdStr(ids);
		tp.setDownloadWay(DownloadWay);
		tp.setCancelReceiver(cancelReceiver);
		tp.setIsCancelMessage(isCancelMessage);
		tp.setCancelTemplate(cancelTemplate);
		boolean flag = gatewayInsureService.copyAddTradInsuPlan(tp,oldPlanNo,isCopy);
		//boolean flag = false;
		if(flag){
			logger.info("==========================添加投保方案成功=============================");

			//根据方案对应的产品的产品类型，查询相应方案组信息,将该方案和方案组信息维护到方案与方案组关联表
			TradProdInst tradProdInst=new TradProdInst();
			tradProdInst.setTradProdCode(tradProdCode);
			tradProdInst=productService.queryTradProdInst(tradProdInst);//得到产品类型
			
			//根据产品类型得到方案组ID
			TradPlanGroup gp = new TradPlanGroup();
			gp.setProdType(tradProdInst.getTradProdType());
			TradPlanGroup pg = plangroupService.queryTradPlanGroupID(gp);
			
			//维护方案与方案组关联表
			if(pg!=null){
				TradInsuPlanGroup group = new TradInsuPlanGroup();
				group.setInsuPlanNumber(tp.getInsuPlanNo());
				group.setPlanGroupId(StrUtil.getVal(pg.getGroupId()));
				group.setRequired("0");
				boolean f = insuPlanGroupService.addTradInsuPlanGroup(group);
				if(!f){return Result.error("维护方案与方案组关联出错");}
			}
			Map<String,String>  resultMap =new  HashMap<String,String>();
			resultMap.put("InsuPlanNo", tp.getInsuPlanNo());
			resultMap.put("AgentType", prod2.getAgentType());
			return Result.successAndData("添加成功",resultMap);
		}else{
			logger.info("==========================添加投保方案失败=============================");
			return Result.error("添加失败");
		}
	}
}
